var counter = 0; //定时运行次数 == 消耗时间秒数
var submitStatus = "未交卷"; //未交卷, 交卷中, 已交卷, 交卷失败
var answer = [];
const isForm = getQueryString('isFrom')
const er_id = getQueryString('er_id')
const user_id = getQueryString('user_id')
var ep_id;
var eq1_ids;
var eq2_ids;


var userInfo = {};
var url = location.href;

//  alert(location.href);
// function initConst(info) {
//     userInfo = info;
//     user_id = userInfo.emplId
// }

$(function () {
	initData();
    console.log('er_id is ' + er_id + ', user_id is ' + user_id)
    initExamList();
})

function initExamList() {
    getExamData();
};

function initData() {
    var data = {
	    "er_state":2,
	    "er_mark":0,
	    "eq2_res":",,,,,,,,,",
	    "er_id":11,
	    "user_id":"065506030123353335",
	    "ere_time":"2018-08-29 18:33:54",
	    "ers_time":"2018-08-29 18:03:54",
	    "eq2_obj":[
		    {
			    "op_d":"1100元",
			    "op_a":"500元",
			    "tags":"普法",
			    "eq_id":28,
			    "op_c":"1000元",
			    "level":0,
			    "op_b":"800元",
			    "answer":"B",
			    "question":"甲、乙签订一份合同，双方约定任何一方违约应向对方支付违约金500元。为担保合同的履行，甲又向乙支付了300元定金。后来乙完全不履行合同，但未给甲造成实际经济损失。按照相关规定乙应向甲支付( )人民币。"
		    },
		    {
			    "op_d":"经重新考试合格后，旅游行政部门可对其颁发临时导游证 ",
			    "op_a":"不得再参加导游资格考试",
			    "tags":"普法",
			    "eq_id":34,
			    "op_c":"经重新考试合格后，旅游行政部门可对其颁发导游证",
			    "level":0,
			    "op_b":"经重新考试合格后，旅游行政部门仍不得对其颁发导游证",
			    "answer":"B",
			    "question":"《导游人员管理条例》规定，被吊销过导游证的人员( )。"
		    },
		    {
			    "op_d":"未经批准或者未按照规定登陆、住宿的",
			    "op_a":"持有他人出境、入境证件的",
			    "tags":"普法",
			    "eq_id":36,
			    "op_c":"外国船舶未经许可停靠在非对外开放港口的",
			    "level":0,
			    "op_b":"侮辱边境检查人员的",
			    "answer":"A",
			    "question":"对出入境人员可以处以500元以上2000元以下罚款的情形是( )。"
		    },
		    {
			    "op_d":"3年",
			    "op_a":"半年",
			    "tags":"普法",
			    "eq_id":29,
			    "op_c":"2年",
			    "level":0,
			    "op_b":"1年",
			    "answer":"B",
			    "question":"当事人请求变更、撤销合同应当向有管辖权的人民法院或仲裁机构，在知道或应当知道撤销事由之日起( )内提出申请。"
		    },
		    {
			    "op_d":"30日",
			    "op_a":"7日",
			    "tags":"普法",
			    "eq_id":31,
			    "op_c":"15日",
			    "level":0,
			    "op_b":"10日",
			    "answer":"C",
			    "question":"旅游行政管理部门对于符合条件申领导游证的，必须在收到申请书之日起( )内颁发导游证。"
		    },
		    {
			    "op_d":"150元",
			    "op_a":"10元",
			    "tags":"普法",
			    "eq_id":35,
			    "op_c":"100元",
			    "level":0,
			    "op_b":"50元",
			    "answer":"B",
			    "question":"旅游者章先生与L旅行社签订了一份旅游合同，并交纳了500元预付款。在出发前一天章先生得知，因L旅行社停业整顿不能成行，根据《旅行社质量保证金赔偿试行标准》的规定，L旅行社应赔偿章先生的违约金是( )。"
		    },
		    {
			    "op_d":"承诺必须在要约的有效期限内做出",
			    "op_a":"承诺可以撤回",
			    "tags":"普法",
			    "eq_id":30,
			    "op_c":"承诺应以通知的方式做出",
			    "level":0,
			    "op_b":"承诺是希望和他人订立合同的意思表示",
			    "answer":"A",
			    "question":"关于承诺，下列说法不正确的是( )。"
		    },
		    {
			    "op_d":"先履行抗辩权",
			    "op_a":"撤销权",
			    "tags":"普法",
			    "eq_id":27,
			    "op_c":"同时履行抗辩权",
			    "level":0,
			    "op_b":"后履行抗辩权",
			    "answer":"D",
			    "question":"甲旅行社与乙饭店签订一份客房租赁合同，约定先住宿后付费。合同签订后乙有确切证据证明甲的财产及经营状况恶化。根据《合同法》的规定，乙可以行使( )"
		    },
		    {
			    "op_d":"150元",
			    "op_a":"10元",
			    "tags":"普法",
			    "eq_id":33,
			    "op_c":"100元",
			    "level":0,
			    "op_b":"50元",
			    "answer":"C",
			    "question":"旅游者刘女士在H旅行社组织的旅游活动过程中，被导游人员小王索要小费50元，根据《旅行社质量保证金赔偿试行标准》的规定，H旅行社应赔偿刘女士( )。"
		    },
		    {
			    "op_d":"2分",
			    "op_a":"10分",
			    "tags":"普法",
			    "eq_id":32,
			    "op_c":"6分",
			    "level":0,
			    "op_b":"8分",
			    "answer":"C",
			    "question":"导游人员魏某因自身的原因漏接旅游团的行为，应被扣除( )。"
		    }
	    ],
	    "eq1_res":",,,,,,,,,V",
	    "eq3_res":"",
	    "eq1_ids":"22,18,19,20,23,26,21,24,25,17",
	    "er_surp":-21,
	    "eq3_obj":[

	    ],
	    "eq2_ids":"31,35,34,33,36,30,29,27,28,32",
	    "eq1_obj":[
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":23,
			    "question":"非全日制用工，是指以小时计酬为主，劳动者在同一用人单位一般平均每日工作时间不超过四小时，每周工作时间累计不超过二十小时的用工形式。"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":24,
			    "question":"事业单位与实行聘用制的工作人员订立、履行、变更、解除或者终止劳动合同，法律、行政法规或者国务院另有规定的，依照其规定；未作规定的，依照《民法通则》有关规定执行。"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":26,
			    "question":"劳务派遣单位应当与被派遣劳动者订立半年以上的固定期限劳动合同，按月支付劳动报酬。"
		    },
		    {
			    "answer":"V",
			    "level":0,
			    "tags":"普法",
			    "eq_id":20,
			    "question":"劳动者主动向用人单位提出解除劳动合同并与用人单位协商一致解除劳动合同的,用人单位不必向劳动者支付经济补偿。"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":22,
			    "question":"非全日制用工双方当事人不得订立口头协议"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":18,
			    "question":"任何组织或者个人对违反《劳动合同法》的行为都有权申请调解，县级以上人民政府劳动行政部门应当及时核实、处理。"
		    },
		    {
			    "answer":"V",
			    "level":0,
			    "tags":"普法",
			    "eq_id":17,
			    "question":"经济补偿按劳动者在本单位工作的年限，每满一年支付一个月工资的标准向劳动者支付。"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":25,
			    "question":"劳务派遣单位派遣劳动者应当与接受以劳务派遣形式用工的单位订立劳动合同"
		    },
		    {
			    "answer":"X",
			    "level":0,
			    "tags":"普法",
			    "eq_id":19,
			    "question":"用人单位违法解除或者终止劳动合同，劳动者要求继续履行劳动合同的，用人单位可以支付赔偿金"
		    },
		    {
			    "answer":"V",
			    "level":0,
			    "tags":"普法",
			    "eq_id":21,
			    "question":"用人单位经济性裁员时，应当优先留用订立无固定期限劳动合同的人员"
		    }
	    ],
	    "eq3_ids":"",
	    "plan":{
		    "eq2_cnt":10,
		    "epe_time":"2018-08-31 23:55:00",
		    "tags":"普法",
		    "ep_id":4,
		    "eq3_val":0,
		    "ep_limit":30,
		    "ep_type":"一试一卷",
		    "eq1_cnt":10,
		    "eq2_val":5,
		    "ep_name":"普法考试",
		    "ep_desc":"",
		    "eq3_cnt":0,
		    "eq1_val":5,
		    "eps_time":"2018-08-24 08:55:00",
		    "status":5,
		    "created":"2018-08-24 08:55:29"
	    }
    };

	console.log(data);
	eq1_ids = data.eq1_ids ;
	eq2_ids = data.eq2_ids ;
	ep_id = data.plan.ep_id;
	const exam = convertAPIDataToExam(data)
	//set selected
	exam.question = exam.question.map(function(item){
		item.qList.map(function(qItem){
			qItem.items.map(function(x){
				if(qItem.uAnswer){
					x.selected =  qItem.uAnswer === x.key
				}
				return x;
			})
			answer.push({id: qItem.id, userAnswerKey: qItem.uAnswer ? qItem.uAnswer : ''})
			return qItem;
		})
		return item
	})
	if(!exam.uScore && exam.remainingSecond <= 0){ //0分 --> 未答 或 未提交
		console.log('已过答题时间 将 status 设置为已考完')
		exam.status = '已考完'
	}
	console.log(exam.status)
	initListHeader(exam);
	initListBodyForExamed(exam);
	initListFooter(exam);
}

function getExamData() {
    //TODO
    $.get('http://localhost:8222/exam/test?er_id=' + er_id, function(data){
        console.log(data);
        eq1_ids = data.eq1_ids ;
        eq2_ids = data.eq2_ids ;
        ep_id = data.plan.ep_id;
        const exam = convertAPIDataToExam(data)
        //set selected
        exam.question = exam.question.map(function(item){
            item.qList.map(function(qItem){
                qItem.items.map(function(x){
                    if(qItem.uAnswer){
                        x.selected =  qItem.uAnswer === x.key
                    }
                    return x;
                })
                answer.push({id: qItem.id, userAnswerKey: qItem.uAnswer ? qItem.uAnswer : ''})
                return qItem;
            })
            return item
        })
        if(!exam.uScore && exam.remainingSecond <= 0){ //0分 --> 未答 或 未提交
            console.log('已过答题时间 将 status 设置为已考完')
            exam.status = '已考完'
        }
        console.log(exam.status)
        initListHeader(exam);
        initListBodyForExamed(exam);
        initListFooter(exam);
    });
};

function convertAPIDataToExam(data) {
    const exam = {
        examId: data.er_id,
        title: data.plan.ep_name,
        limit: data.plan.ep_limit,
        status: getStatus(data.er_state),
        remainingSecond: getRemainingSecond(data.plan.epe_time), 
        uScore: data.er_mark,
        question: getQuestions(data)
    };
    exam.totalScore = getTotalScore(exam.question);
    console.log(exam);
    return exam;
}

function getTotalScore(data){ 
    const allScore = data.map(function(item){
        return item.typeScore
    }).reduce(function(a,b){
        return a + b
    })
    return allScore;
}

function getStatus(status){ 
    return status === 5 ? "已考完" : "考试中" //考试中, 已考完
}

function getRemainingSecond(endTime){ 
    const endTimeStamp = newDate(endTime).getTime()
    const currentTimeStamp = Date.now()
    return parseInt((endTimeStamp - currentTimeStamp) / 1000); //剩余秒数 -- status === '考试中' 才有意义
}

function getQuestions(data){
    const questions = [];
    const sInfo = {
        indexTxt: '一',
        key: '选择题',
        averageScore: data.plan.eq2_val, //每题分数
        typeScore: data.plan.eq2_val * data.plan.eq2_cnt,//类型总分
        qList: getDetailQList(data.eq2_obj, data.eq2_res, data.eq2_ids, '选择题')
    };//选择题
    questions.push(sInfo)
    const jInfo = {
        indexTxt: '二',
        key: '判断题',
        averageScore: data.plan.eq1_val, //每题分数
        typeScore: data.plan.eq1_val * data.plan.eq1_cnt,//类型总分
        qList: getDetailQList(data.eq1_obj, data.eq1_res, data.eq1_ids, '判断题')
    };//判断题
    questions.push(jInfo)
    return questions;
}


function getDetailQList(data, res, sortIds, type){
    const rIdList = sortIds.split(","); //保证顺序一致
    console.log(res)
    const rResList = res.split(","); //保证顺序一致
    const qList = [];
    data.map(function(q){
        const item =  {
            id: q.eq_id,
            showIndex: getShowIndex(q.eq_id, rIdList),
            title: q.question,
            uAnswer: getUAnswer(q.eq_id, rIdList, rResList), //用户的答案
            answer: q.answer, //题目的 answer
        };
        item.items = getSelectItems(q, type, item.answer)
        item.isRight = item.uAnswer === item.answer //是否答题正确
        qList.push(item);
        return q;
    })
    return qList.sort(function(a,b) { //以显示顺序排序
        return a.showIndex - b.showIndex
    });
}

function getSelectItems(data, type, answer){
    var items = []
    if(type === '判断题'){
        items = [
            {
                key: 'V',
                value: ''
            },
            {
                key: 'X',
                value: ''
            }
        ]
    }
    else { //选择题
        items = [
        {
            key: 'A',
            value: data.op_a
        },
        {
            key: 'B',
            value: data.op_b
        },
        {
            key: 'C',
            value: data.op_c
        },
        {
            key: 'D',
            value: data.op_d
        }]
        
    }
   return items.map(function(item){
    item.isRightAnswer = item.key === answer
    return item
})
}

function getShowIndex(id, rIdList){
    var returnId;
    for(var i=0; i<rIdList.length; i++){
        if(Number(rIdList[i]) === id) {
            returnId = i + 1;
        }
    }
    console.log('----')
    console.log(returnId)
    return returnId;
}

function getUAnswer(id, rIdList, rResList){
    console.log(rResList)
    const list = [];
    for(var i=0; i<rIdList.length; i++){
        list.push({id: rIdList[i], res:rResList[i]})
    }
    console.log(list)
    console.log(list.find(function(item){
        return item.id === id;
    }))
    return list.find(function(item){
        return Number(item.id) === id;
    }).res
}

function getLastEqRes(answer, ids){
    const realAnswerList = [];
    ids.split(',').map(function(id){
        const userA = answer.find(function(item){
            return Number(item.id) === Number(id);
        }).userAnswerKey
        console.log(userA)
        realAnswerList.push(userA)
        return id
    })
    return realAnswerList.reduce(function(a,b){
         return a + ',' + b
    })
}

function initListHeader(exam) {
    var list_header_template = [
        '<div class="weui-panel weui-panel_access test">',
        '<div class="weui-panel__bd">',
        '<a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">',
        '<div class="weui-media-box__bd">',
        '<h4 class="weui-media-box__title">{{title}}</h4>',
        '<p class="weui-media-box__desc">（总分：{{totalScore}}分, 考试时长: {{limit}}分）</p>',
        '</div>',
        '</a>',
        '</div>',
        '</div>',
    ].join('');
    //初始化这个模板
    Mustache.parse(list_header_template);
    $("#list_header").html(Mustache.render(list_header_template, exam))
};

function initListBodyForExamed(exam) {
    const list_body_template = [
        '{{#data}}<div class="weui-panel weui-panel_access test">',
        '<div class="weui-panel__hd">{{indexTxt}}、{{key}} (每题{{averageScore}}分, 总共{{typeScore}}分)</div>',
        '<div class="weui-panel__bd">',
        '{{#qList}}<span href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">',
        '<div class="weui-media-box__bd">',
        '{{^isRight}}<img class="rel_img" src="../img/cuo.png"/>{{/isRight}}',
        '{{#isRight}}<img class="rel_img" src="../img/dui.png"/>{{/isRight}}',
        '<p class="weui-media-box__desc">{{showIndex}}. {{title}}</p>',
        '<div class="weui-cells weui-cells_radio">',
        '{{#items}}<label class="weui-cell weui-check__label" for="radio{{id}}{{key}}">',
        '<div class="weui-cell__bd">',
        '{{#isRightAnswer}}<div class="item_answer_div">{{key}}. {{value}} </div>{{/isRightAnswer}}',
        '{{^isRightAnswer}}{{#selected}}<div class="item_selected_div">{{key}}. {{value}} </div>{{/selected}}{{/isRightAnswer}}',
        '{{^isRightAnswer}}{{^selected}}<div class="item_div">{{key}}. {{value}} </div>{{/selected}}{{/isRightAnswer}}',
        '</div>',
        // '<div class="weui-cell__ft">',
        // '{{^selected}}<input type="radio" class="weui-check" name="radio{{id}}" id="radio{{id}}{{key}}" value="{{key}}" onclick="setUserAnswer({{id}}, this.value)">{{/selected}}',
        // '{{#selected}}<input type="radio" class="weui-check" name="radio{{id}}" checked="checked" id="radio{{id}}{{key}}" value="{{key}}" onclick="setUserAnswer({{id}}, this.value)">{{/selected}}',
        // '<span class="weui-icon-checked"></span>',
        // '</div>',
        '</label>{{/items}}',
        '</div>',
        '<p class="answer_p" >  答案 {{answer}}</p>',
        '</div>',
        '</span>',
        '</div>{{/qList}}',
        '</div>{{/data}}',
    ].join('');
    //初始化这个模板
    Mustache.parse(list_body_template);
    const data = exam.question;
    $("#list_body").html(Mustache.render(list_body_template, { data: data }))
}

function initListFooter(exam) {
    var text = '';
    // if(exam.status === '已考完'){
        text = "得分: " + exam.uScore + "分";
        submitStatus = "已交卷"
    // }
    // else {
    //     const time  = Number(exam.remainingSecond) ;
    //     const timeTxt = getTimeText(time) 
    //     text = timeTxt + "&nbsp; &nbsp; 交&nbsp;卷";
    // }
    console.log(text)
    $("#btn-submit").html(text);
};

function finishExam(){
    //
    console.log(submitStatus)
    // console.log('重新考试')
    // window.location = 'test.html?ep_id=' + ep_id + '&user_id=' + user_id;
}

function setUserAnswer(id, key) {
    console.log('---------')
    console.log(id);
    console.log(key);
    // answer = answer.filter(function(item){
    //     return item.id !== id
    // })
    // answer.push({id, userAnswerKey: key})
    // console.log(answer)
    // loopUserAnswer()
};

// function backToList() {
//     if(isForm === 'myList') {
//         window.location = 'myTestList.html'
//     }

//     if(isForm === 'center') {
//         window.location = 'center.html'
//     }
// }

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function newDate(strdate) {  
    var arr = strdate.split(/[- : \/]/);  
    console.log(arr);
    date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);  
    return date;  
} 